package com.ly.hotel.view.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ly.hotel.R;
import com.ly.hotel.adaptor.HardwareInterface;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.model.Ad;
import com.ly.hotel.model.AdDetail;
import com.ly.hotel.msgevent.CloudAdShowFinishEvent;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.msgevent.SetVodPlayEvent;
import com.ly.hotel.util.AppUtil;
import com.ly.hotel.util.ImageUtil;
import com.ly.hotel.view.fragments.vod.NativeVideoPlayerActivity;
//import com.ly.hotel.view.live.TvActivity1;
/*import com.ly.hotel.vitamio.VideoViewDemo;
*/
import de.greenrobot.event.EventBus;
//全屏广告播放
public class CloudAdShowActivity extends Activity {
	public LinearLayout adShowLayout;
	private TextView countDownTextView;
	public CountDownTimer timer;
	private Handler handler;

	// 播放的类型 
	public String actionType;

	/* 播放电影需要的参数 */
	protected Intent mIntent;
	public String filmName;
	public String path;
	public int filmId;
	public String filmArea;
	public Integer position;
	public String nextVodsList;
	private MyApplication app;
	
	/* 播放全屏电视需要的参数 */
	public String apkName;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_ad_show);
		app = (MyApplication) getApplicationContext();
		adShowLayout = (LinearLayout) findViewById(R.id.adShowLayout);
		countDownTextView = (TextView) findViewById(R.id.myTextView);

		mIntent = getIntent();

		actionType = mIntent.getStringExtra("actionType");

		if (actionType.equals("vod")) {
			filmName = mIntent.getStringExtra("filmName");
			filmArea = mIntent.getStringExtra("filmArea");
			path = mIntent.getStringExtra("path");
			filmId = mIntent.getIntExtra("filmId", -1);
			position = mIntent.getIntExtra("position", 0);
			nextVodsList   = mIntent.getStringExtra("nextVodsList");
		} else if (actionType.equals("tv")) {
//			curLive = (LiveManagement) getIntent().getSerializableExtra("curLive");
		} else if (actionType.equals("tv_3td")) {
			apkName = mIntent.getStringExtra("apkName");
		}

		Log.e("cloud-ad-show", "检测有没有广告->" + actionType);
		handler = new Handler();

		HardwareInterface.setMuteFlag(false);
	}

	@Override
	protected void onPause() {
		sendBroadcast(new Intent(Constants.Broadcast.CALL_MENU).putExtra("flag", Constants.POINT_OPEN));
		super.onPause();
	}

	@Override
	protected void onResume() {
		if (actionType.equals("vod")) {
			if (AdData.getVod() != null) {
				Log.i("cloud-ad-show", "播放电影广告");
				showAd(AdData.getVod());
			} else {
				// 没有广告，就直接播放
				Log.i("cloud-ad-show", "没有广告，直接播放");
				enter();
			}
		} else if (actionType.equals("tv")) {
			if (AdData.getTv() != null) {
				showAd(AdData.getTv());
			} else {
				// 没有广告，就直接播放
				Log.i("cloud-ad-show", "没有广告，直接播放");
				enter();
			}
		} else if (actionType.equals("tv_3td")) {
			if (AdData.getTv() != null) {
				showAd(AdData.getTv());
			} else {
				// 没有广告，就直接播放
				Log.i("cloud-ad-show", "没有广告，直接播放");
				enter();
			}
		}else {
			Log.i("cloud-ad-show", "不合法的类型");
			enter();
		}

		super.onResume();
		Log.e("cloud-ad-show", "onResume");
	}

	@Override
	public void onBackPressed() {
	}

	@SuppressLint("DefaultLocale")
	private void playVod() {
		Log.i("cloud-ad-show", "将要播放" + filmName);
		if (path != null) {
			path.replaceAll(";", "%3b");
			/*if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA628_NAME) || Build.BOARD.endsWith(Constants.BOARD_TYPE_6A638_NAME)
					 || Build.BOARD.endsWith(Constants.BOARD_TYPE_6A648_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_ADA648_NAME)){
		           String strend="";
		           if(path.toLowerCase().endsWith(".mp4")){  
		               strend="mp4";  
		           }else if(path.toLowerCase().endsWith(".3gp")){  
		               strend="3gp";  
		           }else if(path.toLowerCase().endsWith(".mov")){  
		               strend="mov";  
		           }else if(path.toLowerCase().endsWith(".wmv")){  
		               strend="wmv";  
		           }else if(path.toLowerCase().endsWith(".mkv")){  
		               strend="mkv";  
		           }else if(path.toLowerCase().endsWith(".rmvb")){  
		               strend="rmvb";  
		           }else if(path.toLowerCase().endsWith(".rm")){  
		               strend="rm";  
		           }   
		           
		           if(filmId >= 0){
						Log.i("vod", "开始播放电影");
						EventBus.getDefault().post(new SetVodPlayEvent(filmId, SetVodPlayEvent.START));
						EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_VOD_PREFIX + "首次播放" + "\t" + filmArea + "\t" + filmName));
		           }
		           
		           Intent intent = new Intent();    
		           intent.setAction(Intent.ACTION_VIEW);
		           intent.setDataAndType(Uri.parse(path), "video/"+strend);  
		           intent.setComponent(new ComponentName("com.pre.localmm","com.pre.localmm.ui.video.VideoPlayerActivity"));  
		           intent.putExtra("maxVolume", HardwareInterface.getMaxVolume());
		           intent.putExtra("filmId", filmId);
		           //如果有历史记录的，就通知播放器从上次结束时开始播放,播放进度已经在播放器那边保存了
		           if(filmId >= 0){
			   			for(Vodvideo vv : app.vodHistory){
			   				if(vv.getId().equals(filmId)){
			   					Log.i("cloud-ad-show", "getPlayPosition->" + vv.getPlayPosition());
			   					if(vv.getPlayPosition().equals(1)){
				   					vv.setPlayPosition(0);//权宜之计啊，628用的是外部的播放器。需要在这里设置一下不为0，这样下一次播放器就会跳到上一次的播放位置了
				   					Log.i("cloud-ad-show", "断点播放->" + filmId + ",片名->" + vv.getName());
//				   					intent.putExtra("isNeedBreakPointPlayBySpa", true);
			   					}
			   				}
			   			}
		           }
		           startActivity(intent);  
		        HardwareInterface.setMuteFlag(false);
		             
			} else {*/
				Log.i("cloud-ad-show", filmName + ", url=" + path);
				if(filmId >= 0){
					Log.i("cloud-ad-show", "开始播放电影");
					EventBus.getDefault().post(new SetVodPlayEvent(filmId, SetVodPlayEvent.START));
					EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_VOD_PREFIX + "首次播放" + "\t" + filmArea + "\t" + filmName));
				}
				
				if(app.mySpaceIsKey("film" + filmId).equals("true")){
					position = Integer.valueOf(app.mySpaceGetValue("film" + filmId));
					Log.i("cloud-ad-show", "获取播放位置=" + position);
				}
				
				Intent intent = new Intent(this, NativeVideoPlayerActivity.class);
				intent.putExtra("path", path);
				intent.putExtra("filmName", filmName);
				intent.putExtra("filmId", filmId);
				intent.putExtra("filmArea", filmArea);
				intent.putExtra("position", position);
				intent.putExtra("nextVodsList", nextVodsList);
				this.startActivity(intent);

//			}
		} else {
			Log.i("cloud-ad-show", "videoUrl=null---请联系后台管理员添加视频！");
			Toast.makeText(getApplicationContext(), "没有找到该视频", Toast.LENGTH_SHORT).show();
		}
	}

	public void enter() {
		sendBroadcast(new Intent(Constants.Broadcast.CALL_MENU).putExtra("flag", Constants.POINT_OPEN));
		// 清除所有的view，否则会导致进入播放电影的时候，会一闪一闪的三下
		adShowLayout.removeAllViews();

		if (actionType.equals("vod")) {
			playVod();
		} else if (actionType.equals("tv")) {
			if(Build.BOARD.equals(Constants.BOARD_TYPE_ADA801_NAME)){
				AppUtil.startApp(this, "com.ly.atvplayer");
			}else if(Build.BOARD.equals(Constants.BOARD_TYPE_ADA628_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_6A638_NAME)){
				AppUtil.startApp(CloudAdShowActivity.this, "com.mstar.tv.tvplayer.ui");
			}else if(Build.BOARD.equals(Constants.BOARD_TYPE_6A648_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_ADA648_NAME)){
				AppUtil.startApp(CloudAdShowActivity.this, "com.mstar.tv.tvplayer.ui");
			}else {
				Intent intent = new Intent();
				intent.setClassName("com.tcl.tv", "com.tcl.tv.TVActivity");
				Bundle bundle = new Bundle();
				bundle.putInt("targetSourceId", 2);//2 DTV, 3 AV1，4 AV2，8 HDMI1, 9 HDMI2
				intent.putExtras(bundle);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			}
		} else if (actionType.equals("tv_3td")) {
			//第三方的电视apk
			//要解除静音两次。。否则在3128的盒子上会没有声音
			HardwareInterface.setMuteFlag(false);
			HardwareInterface.setMuteFlag(false);
			AppUtil.startApp(CloudAdShowActivity.this, apkName);
		} else {
			Log.i("cloud-ad-show", "不合法的类型");
		}

		finish();
	}

	private void setShowAdCountDownTime(int time) {
		if (countDownTextView != null) {
			Log.i("SPAService", "开机广告时间" + time + "秒");
			timer = new CountDownTimer(time, 1000) {
				@Override
				public void onTick(long millisUntilFinished) {
					countDownTextView.setText("广告 " + (millisUntilFinished / 1000) + " 秒");
				}

				@Override
				public void onFinish() {
					countDownTextView.setText("广告 " + 0 + " 秒");
				}

			}.start();
		}
	}

	private void adPlayVod(final AdDetail adl) {
		// 视频
		String url = adl.localPath; 
		Log.i("cloud-ad-show", "加载视频go..." + url);

		HardwareInterface.setFullScreen();
		MyVideoView videoView = new MyVideoView(this) {
			protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
				int width = getDefaultSize(0, widthMeasureSpec);
				int height = getDefaultSize(0, heightMeasureSpec);
				setMeasuredDimension(width, height);
			}

		};
		videoView.setBackgroundResource(R.color.transparent);
		LinearLayout.LayoutParams fparams = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		videoView.setLayoutParams(fparams);
		videoView.setVideoURI(Uri.parse(url));
		
		videoView.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				if (mp != null) {
					mp.stop();
					// 上报服务器，播放完一次了
					EventBus.getDefault().post(new CloudAdShowFinishEvent(adl.getId()));
				}
//				enter();
				
				//进入主页面
				handler.post(new Runnable() {
					public void run() {
						enter();
					}
				});
			}
		});
		videoView.setOnErrorListener(new OnErrorListener() {

			@Override
			public boolean onError(MediaPlayer mp, int arg1, int arg2) {
				Log.i("cloud-ad-show", "videoView onError");
				mp.stop();
				handler.post(new Runnable() {
					public void run() {
						enter();
					}
				});
				return false;
			}
		});
		videoView.setOnPreparedListener(new OnPreparedListener() {

			@Override
			public void onPrepared(MediaPlayer mp) {
				Log.i("cloud-ad-show", "videoView onPrepared");
				mp.setLooping(false);
				mp.start();
				setShowAdCountDownTime(mp.getDuration());
			}
		});
		adShowLayout.addView(videoView);

	}

	private void adPlayImg(final Ad ad) {
		// 图片

		if (ad.getDetails() != null && ad.getDetails().isEmpty()) {
			Log.i("cloud-ad-show", "没有图片广告可以播放");
//			finish();
			enter();
			return;
		}

		final ImageView imageView = new ImageView(this);
		imageView.setScaleType(ScaleType.FIT_XY);
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		imageView.setLayoutParams(layoutParams);

		adShowLayout.addView(imageView);

		new Thread(new Runnable() {

			@Override
			public void run() {
				final List<Bitmap> imgs = new ArrayList<Bitmap>();
				final Map<Bitmap, Integer> imagesIntervalMap = new HashMap<Bitmap, Integer>();
				// 加载图片
				for (AdDetail detail : ad.getDetails()) {
					if (detail.getType() == AdDetail.PIC && detail.isEnable() && detail.isCache) {
						Log.i("cloud-ad-show", "加载图片,url=" + detail.localPath);
						Bitmap loadImage = ImageUtil.loadImage(CloudAdShowActivity.this, detail.localPath);
						if (loadImage != null) {
							Log.i("cloud-ad-show", "显示时间=" + detail.getSwitchTime());
							imgs.add(loadImage);
							imagesIntervalMap.put(loadImage, detail.getSwitchTime() * 1000);
						} else {
							Log.i("cloud-ad-show", "加载图片失败..." + detail.getPath());
						}
					}
				}
				if (imgs.isEmpty()) {
//					finish();
					enter();
					return;
				}
				Log.i("cloud-ad-show", "轮播图片加载完成.");
				CloudAdShowActivity.this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						MyAnimationDrawable ani = new MyAnimationDrawable() {
							@Override
							public void onFrameEnd(int next) {
								EventBus.getDefault().post(new CloudAdShowFinishEvent(ad.getDetails().get(next).getId()));
							}
						};

						for (Bitmap bm : imgs) {
//							Log.i("AdShowActivity", "imagesIntervalMap.get(bm)=" + imagesIntervalMap.get(bm));
							ani.addFrame(new BitmapDrawable(CloudAdShowActivity.this.getResources(), bm),
									imagesIntervalMap.get(bm));
						}
						ani.setOneShot(true);
						imageView.setImageDrawable(ani);
						ani.start();
						sendBroadcast(new Intent(Constants.Broadcast.CALL_MENU).putExtra("flag", Constants.POINT_CLOSE));
						// progressDialog.cancel();
						// 计算总共显示的时间
						int duration = 0;
						for (int i = 0; i < ani.getNumberOfFrames(); i++) {
							Log.i("cloud-ad-show", "ani.getDuration=" + ani.getDuration(i));
							duration += ani.getDuration(i);
						}

						if(duration > 1*1000){
							//提早一点进入界面，这样才不会导致显示太长时间的切换背景
							duration = duration - 1*1000;
						}
						
						if(duration < 1*1000){
							duration = 1000;
						}
						// 时间到就进入主页面
						handler.postDelayed(new Runnable() {
							public void run() {
								enter();
							}
						}, duration);

						setShowAdCountDownTime(duration);
					}
				});

			}
		}).start();

	}

	private void showAd(final Ad ad) { 
		// ad.getDetails().get(0).getType());
		// 确定是否有视频，有视频就不要采用图片的了
		for (AdDetail adl : ad.getDetails()) { 
			Log.i("cloud-ad-show","getType=" + "adl.getType()" + ",isEnable=" + adl.isEnable() + ",isCache=" + adl.isCache);
			Log.i("cloud-ad-show","dl.localPath=" + adl.localPath);
			if (adl.getType() == AdDetail.VIDEO && adl.isEnable() && adl.isCache && !adl.localPath.equals("")) {
				Log.i("cloud-ad-show",adl.localPath);
				sendBroadcast(new Intent(Constants.Broadcast.CALL_MENU).putExtra("flag", Constants.POINT_CLOSE));
				adPlayVod(adl);
				return;
			}
		}
		
		Log.i("cloud-ad-show","没有视频广告，尝试播放图片广告。。");
		adPlayImg(ad);
	}

}
